<template>
  <div class="media-data">
    <a-form-model ref="ruleForm" :rules="rules" :model="ruleForm">
      <a-row justify="space-between">
        <a-col :span="4" :xxl="4" :xl="4" :lg="4">
          <a-form-model-item has-feedback label="名称" prop="name" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 1 }">
            <a-input v-model="ruleForm.name" allow-clear placeholder="请输入" />
          </a-form-model-item>
        </a-col>
        <!-- <a-col :span="8">
          <a-form-model-item has-feedback label="时间区间" prop="range" :labelCol="{ span: 4 }" :wrapperCol="{ span: 18, offset: 1 }">
            <a-range-picker @change="handleTimeChange" :placeholder="['开始日期', '结束日期']" v-model="ruleForm.range" />
          </a-form-model-item>
        </a-col> -->
        <a-col :span="12" :xxl="12" :xl="12" :lg="20">
          <div style="dispaly: flex;">
            <span style="margin-right:1rem;">时间区间: </span>
            <a-date-picker :inputReadOnly="true" :allowClear="false" v-model="ruleForm.startTime" show-time />
            -
            <a-date-picker :inputReadOnly="true" :allowClear="false" v-model="ruleForm.endTime" show-time />
          </div>
        </a-col>
        <a-col :span="2" push="4">
          <a-form-model-item>
            <a-space>
              <a-button @click="resetForm('ruleForm')">
                重置
              </a-button>
              <a-button :loading="isLoading" type="primary" @click="submitForm('ruleForm')">
                查询
              </a-button>
            </a-space>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-row justify="space-between">
      <a-col :span="24">
        <h3>详情列表</h3>
      </a-col>
    </a-row>
    <a-table
      :loading="isLoading"
      :pagination="pagination"
      @change="handleTableChange"
      @expand="expand"
      :rowKey="(record) => record.appKey"
      :columns="columns"
      :data-source="data"
    >
      <a-table
        :loading="innerIsLoading"
        slot="expandedRowRender"
        slot-scope="record"
        :columns="innerColumns"
        :rowKey="(record) => record.appKey"
        :data-source="record.innerData"
        :pagination="false"
      >
        <span slot="customUv" slot-scope="_, record">
          <span>{{
            record.activityShowUv ? (record.activityShowUv == 0 ? '-' : (record.activityJoinPv / record.activityShowUv).toFixed(2)) : '-'
          }}</span>
        </span>
        <span slot="advertClickRate" slot-scope="_, record">
          <span>{{ record.advertShowPv == 0 ? 0 : ((record.advertValidClick / record.advertShowPv) * 100).toFixed(2) }}%</span>
        </span>
      </a-table>
      <span slot="appName" slot-scope="_, record">
        <span>{{ record.appName == '' ? '-' : record.appName }}</span>
      </span>
      <span slot="activityShowUv" slot-scope="_, record">
        <span>{{ record.activityShowUv || '-' }}</span>
      </span>
      <span slot="customUv" slot-scope="_, record">
        <span>{{
          record.activityShowUv ? (record.activityShowUv == 0 ? '-' : (record.activityJoinPv / record.activityShowUv).toFixed(2)) : '-'
        }}</span>
      </span>
      <span slot="advertClickRate" slot-scope="_, record">
        <span>{{ record.advertShowPv == 0 ? 0 : ((record.advertValidClick / record.advertShowPv) * 100).toFixed(2) }}%</span>
      </span>
      <a slot="action" href="javascript:;">Delete</a>
      <!-- <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
        {{ record.appName }}
      </p> -->
    </a-table>
  </div>
</template>

<script>
import { columns, innerColumns } from './MediaDatas'
import { getAppData, getAppDataDay } from '@/api/MeidaMan/api'
import 'moment/locale/zh-cn'
import moment from 'moment'
export default {
  name: 'MediaData',
  data() {
    return {
      data: [],
      columns,
      isLoading: false,
      innerIsLoading: false,
      innerData: [],
      innerColumns,
      id: '',
      key: '',
      ruleForm: {
        name: '',
        startTime: moment(moment().format('YYYY-MM-DD')),
        endTime: moment(moment().format('YYYY-MM-DD')).add(1, 'days'),
      },
      pageNo: 1,
      pageSize: 100,
      total: 0,
      rules: {},
      pagination: {
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        defaultPageSize: 100,
        showTotal: (total) => `总共  ${total} 条`, // 显示总数
      },
    }
  },
  filters: {
    /**
     * @func 处理文字
     */

    filersText(val) {
      return val == '' ? '-' : val
    },
  },
  created() {},
  mounted() {
    const urlString = location.href
    if (urlString.indexOf('=') != -1) {
      this.queryUrlSearch(urlString) // 处理参数
    }
    const { appKey: key } = this.$route.query
    this.$nextTick(() => {
      this.appData({ key })
    })
  },
  methods: {
    moment,
    /**
     * @func 展开时调用
     */
    expand(_, record) {
      const { appKey: key } = record
      const { startTime: start, endTime: end } = this.ruleForm
      const startTime = moment(moment(start).format('YYYY-MM-DD')).valueOf()
      const endTime = moment(moment(end).format('YYYY-MM-DD')).valueOf()
      this.appDataDay({ key, startTime, endTime })
    },
    /**
     * @func 嵌套列表数据
     */
    async appDataDay(param) {
      this.innerIsLoading = true
      const [err, innerData] = await getAppDataDay({ ...param })
      if (!err) {
        console.log(innerData)
        this.innerIsLoading = false
        innerData.map((item) => {
          item.computeTime = moment(item.computeTime).format('YYYY-MM-DD')
        })
        if (innerData.length) {
          const adId = innerData[0].appKey
          const i = this.data.findIndex((item) => {
            return item.appKey === adId
          })
          this.data = [...this.data.slice(0, i), { ...this.data[i], innerData: innerData }, ...this.data.slice(i + 1)]
          console.log(this.data)
        }
      } else {
        this.innerIsLoading = false
        this.$msgErr(err)
      }
    },
    /**
     * @func 查询应用数据列表
     */
    async appData(param) {
      this.isLoading = true
      try {
        const {
          detailsData: { list, count },
          totalData: { totalActivityShowPv, totalActivityShowUv, totalActivityJoinPv, totalAdvertValidClick, totalAdvertShowPv },
        } = await getAppData({ ...param })
        const pager = { ...this.pagination }
        pager.total = count
        this.isLoading = false
        if (list) {
          const obj = {
            appName: '总数据',
            activityShowPv: totalActivityShowPv,
            activityShowUv: totalActivityShowUv,
            activityJoinPv: totalActivityJoinPv,
            advertShowPv: totalAdvertShowPv,
            advertValidClick: totalAdvertValidClick,
            appKey: 'all',
          }
          if (this.pageNo == 1) {
            this.data = [obj, ...list] ?? []
          } else {
            console.log(list)
            this.data = list ?? []
          }
        }
        this.pagination = pager
      } catch (err) {
        this.isLoading = false
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 查询数据
     */
    submitForm() {
      const rangeValue = this.ruleForm
      const key = this.key
      const { startTime: start, endTime: end, name } = rangeValue
      const startTime = moment(start).valueOf()
      const endTime = moment(end).valueOf()
      const values = {
        name,
        startTime,
        endTime,
        key,
      }
      this.appData(values)
      this.ruleForm.startTime = startTime
      this.ruleForm.endTime = endTime
    },
    /**
     * @func 重置表单
     */
    resetForm() {
      this.ruleForm.name = ''
      this.ruleForm.startTime = moment(moment().format('YYYY-MM-DD'))
      this.ruleForm.endTime = moment(moment().format('YYYY-MM-DD')).add(1, 'days')
      const key = this.key
      this.appData({ key })
    },
    /**
     * @func 时间选择
     */
    handleTimeChange(_, dateStrings) {
      this.ruleForm.startTime = moment(dateStrings[0]).valueOf()
      this.ruleForm.endTime = moment(dateStrings[1]).valueOf()
    },
    /**
     * @func 分页处理
     */
    async handleTableChange(pagination) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      const { name, startTime, endTime } = this.ruleForm
      this.pageNo = pagination.current
      this.appData({ pageNo: pagination.current, pageSize: pagination.pageSize, name, startTime, endTime })
    },
    /**
     * @func 获取url参数
     */
    queryUrlSearch(urlString) {
      console.log(urlString)
      const urlArr = urlString.split('=')
      console.log(urlArr)
      this.key = urlArr[1]
    },
  },
}
</script>

<style>
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
